<!--组件-API-->
<template>
  <div class="wrapper">
    <template  v-if="api">
      <div class="row acenter" @click="apiClick">
        <LImage class="exchange-image" :src="config.img('v2_'+api.exchangeName.toLowerCase()+'.png')"></LImage>
        <div class="column">
          <text class="font28 text1">{{api.apiName}}</text>
          <text class="font20 text2" v-if="api.remarks && api.remarks.length">{{'(' + api.remarks + ')'}}</text>
        </div>
        <LImage class="arrow-image" :src="config.img('xiala.png')"></LImage>
      </div>

      <div class="row acenter" v-if="!trust" @click="rateClick">
        <text class="font24 text1">{{T('手续费') + math.cheng(api.tradeFee, '100') +'%'}}</text>
        <LImage class="edit-image" :src="config.img('editor_white.png')"></LImage>
      </div>
    </template>
  </div>
</template>

<script>

import math from "@/_js/math";

//功能
import navigator from "@/_js/navigator"; 
import broadcast from "@/_js/broadcast"; 
import config from "@/_js/config";
import modal from "@/_js/modal";
import API from "@/_js/api";
import debug from "@/_js/debug";

const weexFunction = weex.requireModule('WeexFunction');
const globalEvent = weex.requireModule('globalEvent');

import I18N from "@/_i18n/i18n";
var T = I18N.t;

export default {

  model:{
    prop:"api",
    event:"change",
  },

  props:{
    api: Object, //选中API

    copyPair: {  //复制配置-交易对
      type:Object,
      default:undefined,
    },

    exchanges: {   //可选交易所“Name”数组
      type:Array,
      default: [],
    },

    noExchanged: {  //不可选交易所对象{name}
      type:Object,
      default: {},
    },
    
    type:{ //0实盘 1模拟盘 -1全显
      type:Number,
      default:-1,
    },

    trust:{ //turn 托管界面使用
      type:Boolean,
      default:false,
    },
  },

  data() {
    return {
      T:T,
      config:config,
      PATH:"https://obs-vt.obs.ap-southeast-1.myhuaweicloud.com/res/weex/strategy/",
      math:math,
      apiTag:'up-api-spot', //API默认配置标识
      isApi:true, //turn有可用实盘API

      api:undefined, //API
      counterCoin:undefined,
      baseCoin:undefined,
    };
  },

  mounted(){
    this.initApiCopy();

    //Api更新通知
    var self = this;
    globalEvent.addEventListener("apiUp",(e)=>{
      if (self.api.apiId == '' && !this.isApi) {
        API.getApis('YES', 'all', this.exchanges, (apis)=>{
          if (self.api.apiId == '' && apis.length) {
            self.initApiCopy();
          }
        });
      } else {
        API.getApi(self.api.apiId, 'all', (api)=>{
          self.setTradeFee(api);
          self.change(api);
        });
      }
    });
  },

  methods:{

    //初始化复制参数api
    initApiCopy() {
      if (!this.copyPair) {
        this.initApi();
        return;
      }

      var exchangeName = this.copyPair.exchangeName;
      API.getMockApi(exchangeName, (api)=>{

        API.getApis('YES', 'all', [exchangeName], (apis)=>{

          api = this.getMockApi(api);
          for (let index = 0; index < apis.length; index++) {
            var data = apis[index];
            if (!data.isFundApi) {
              api = data;
              break;
            }
          }

          this.apiChange(api, this.copyPair.counterCoin, this.copyPair.baseCoin);
        });
      });
    },

    //初始化API
    initApi() {
      
      var mockName = this.exchanges && this.exchanges.length ? this.exchanges[0] : 'Binance';
      API.getMockApi(mockName, (api)=>{
        
        API.getApis('YES', 'all', this.exchanges, (apis)=>{

          weexFunction.getConfig(this.apiTag, (e)=>{
            
            //默认API
            this.isApi = apis.length;
            var counterCoin = 'BTC';
            var baseCoin = 'USDT';
            var config = e.length ? JSON.parse(e) : null;
            if (config) {
              for (let index = 0; index < apis.length; index++) {
                var apix = apis[index];
                if (apix.apiId == config.apiId && 
                config.exchangeName &&
                !this.noExchanged[config.exchangeName.toLowerCase()]) {
                  api = apix;
                  counterCoin = config.counterCoin ? config.counterCoin : counterCoin;
                  baseCoin = config.baseCoin ? config.baseCoin : baseCoin;
                  this.apiChange(api, counterCoin, baseCoin);
                  return;
                }
              }
            }

            //初始化默认API
            api = this.getMockApi(api);
            for (let index = 0; index < apis.length; index++) {
              var data = apis[index];
              if (!data.isFundApi && !this.noExchanged[data.exchangeName.toLowerCase()]) {
                api = apis[index];
                break;
              }
            }

            this.apiChange(api, counterCoin, baseCoin);
          });
        });
      });
    },

    //设置默认Api
    setDefaultApi(apiId, counterCoin, baseCoin) {
      if(apiId.length == 0) {
        return;
      }
      var dict = {'apiId':apiId,
                  'counterCoin':counterCoin, 
                  'baseCoin':baseCoin};
      var str = JSON.stringify(dict);
      weexFunction.setConfig(this.apiTag, str,()=>{});
    },

    /********************************** 其他方法*/
    //改变-绑定值
    change(api){
      this.api = api
      this.$emit("change", api); 
    },

    //获取模拟API
    getMockApi(api) {

      var str = '-' + T('模拟账户');
      var apiName = api.exchangeName + (this.type == 0 ? '' : str);
      var mockApi = {'exchangeName':api.exchangeName,
                    'exchangeId':api.exchangeId,
                    'apiName':apiName,
                    'tradeFee':api.tradeFee,
                    'apiId':''};
      return mockApi;
    },

    //设置手续费
    setTradeFee(api){

      if (!api.tradeFee) {
        API.getMockApi(api.exchangeName, (mockApi)=>{
          api.tradeFee = mockApi.tradeFee;
        });
      }
    },

    //APi改变
    apiChange(api, counterCoin, baseCoin){

      var tipe = this.noExchanged[api.exchangeName.toLowerCase()];
      if(tipe) {
          modal.toast(T(tipe));
        return;
      }
      
      this.setTradeFee(api);
      this.change(api);

      this.counterCoin = counterCoin ? counterCoin : this.counterCoin;
      this.baseCoin = baseCoin ? baseCoin : this.baseCoin;
      this.setDefaultApi(api.apiId, this.counterCoin, this.baseCoin);

      this.$emit("apiChange", counterCoin, baseCoin);
    },
    
    /********************************** 点击触发*/
    //API
    apiClick(){
      
      var menu = this.type;
      if (menu == -1) {
        menu = this.api.apiId == '' ? 1 : 0;
      }
      var param = {'exchangeId':this.api.exchangeId, 
                    'type':this.type, 
                    'supports':this.exchanges,
                    'menu':menu};
      navigator.openDialog('up/SelectApi', param);

      broadcast.subscribeOnce('SelectApi', (api)=>{
        api = api.apiId ? api : this.getMockApi(api);
        this.apiChange(api);
      });
    },

    //手续费
    rateClick(){

      var param = {'apiId':this.api.apiId,
                  'tradeFee':this.api.tradeFee};
      navigator.openDialog('up/ApiFee', param);

      var self = this;
      broadcast.subscribeOnce('ApiFee', (data)=>{
        self.api.tradeFee = data;
      });
    },
  }
}
</script>


<style src="@/_css/style.css"></style>
<style scoped>
.wrapper {
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.exchange-image{
  width: 48px;
  height: 48px;
  margin-right: 20px;
}
.arrow-image{
  width: 20px;
  height: 20px;
  margin-left: 20px;
}
.edit-image{
  width: 32px;
  height: 32px;
  margin-left: 16px;
}
</style>
